package com.zhaoyang.servlet;

import com.zhaoyang.dao.AttendanceDao;
import com.zhaoyang.dao.CourseDao;
import com.zhaoyang.dao.SelectedCourseDao;
import com.zhaoyang.model.*;
import com.zhaoyang.util.DateFormatUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵扬
 * @time 2020/4/28 13:00
 */
@WebServlet("/attendanceServlet")
public class AttendanceServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String method = request.getParameter("method");

        if ("toAttendanceServletListView".equals(method)) {
            try {
                request.getRequestDispatcher("view/attendanceList.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        } else if ("AddAttendance".equals(method)) {
            AddAttendance(request, response);
        } else if ("AttendanceList".equals(method)) {
            attendanceList(request, response);
        } else if ("DeleteAttendance".equals(method)) {
            deleteAttendance(request, response);
        } else if ("getStudentSelectedCourseList".equals(method)) {
            getStudentSelectedCourseList(request, response);
        }
    }

    /**
     * 删除考勤信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteAttendance(HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        AttendanceDao attendanceDao = new AttendanceDao();
        String msg = "success";
        if (!attendanceDao.deleteAttendance(id)) {
            msg = "error";
        }
        response.getWriter().write(msg);
    }

    /**
     * 获取考勤信息列表
     *
     * @param request
     * @param response
     */
    private void attendanceList(HttpServletRequest request,
                                HttpServletResponse response) {
        int studentId = request.getParameter("studentid") == null ? 0 : Integer.parseInt(request.getParameter("studentid").toString());
        int courseId = request.getParameter("courseid") == null ? 0 : Integer.parseInt(request.getParameter("courseid").toString());
        String type = request.getParameter("type");
        String date = request.getParameter("date");
        Integer currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("rows") == null ? 999 : Integer.parseInt(request.getParameter("rows"));

        Attendance attendance = new Attendance();
        //获取当前登录用户类型
        int userType = Integer.parseInt(request.getSession().getAttribute("userType").toString());
        if (userType == 2) {
            //如果是学生，只能查看自己的信息
            Student currentUser = (Student) request.getSession().getAttribute("user");
            studentId = currentUser.getId();
        }

        attendance.setCourseId(courseId);
        attendance.setStudentId(studentId);
        attendance.setDate(date);
        attendance.setType(type);
        AttendanceDao attendanceDao = new AttendanceDao();
        List<Attendance> attendanceList = attendanceDao.getSelectedCourseList(attendance, new Page(currentPage, pageSize));
        long total = attendanceDao.getAttendanceListTotal(attendance);
        response.setCharacterEncoding("UTF-8");
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("total", total);
        ret.put("rows", attendanceList);
        try {
            String from = request.getParameter("from");
            if ("combox".equals(from)) {
                response.getWriter().write(JSONArray.fromObject(attendanceList).toString());
            } else {
                response.getWriter().write(JSONObject.fromObject(ret).toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加考勤信息
     *
     * @param request
     * @param response
     */
    private void AddAttendance(HttpServletRequest request,
                               HttpServletResponse response) {
        int studentId = request.getParameter("studentid") == null ? 0 : Integer.parseInt(request.getParameter("studentid"));
        int courseId = request.getParameter("courseid") == null ? 0 : Integer.parseInt(request.getParameter("courseid"));
        String type = request.getParameter("type");
        AttendanceDao attendanceDao = new AttendanceDao();
        Attendance attendance = new Attendance();
        attendance.setCourseId(courseId);
        attendance.setStudentId(studentId);
        attendance.setType(type);
        attendance.setDate(DateFormatUtil.getFormatDate(new Date(), "yyyy-MM-dd"));
        String msg = "success";
        response.setCharacterEncoding("UTF-8");
        if (attendanceDao.isAttendance(studentId, courseId, type, DateFormatUtil.getFormatDate(new Date(), "yyyy-MM-dd"))) {
            msg = "已签到，请勿重复签到！";
        } else if (!attendanceDao.addAttendance(attendance)) {
            msg = "系统内部出错。请联系管理员！";
        }
        try {
            response.getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取学生选课列表
     *
     * @param request
     * @param response
     */
    private void getStudentSelectedCourseList(HttpServletRequest request,
                                              HttpServletResponse response) {
        String id = request.getParameter("student_id");
        Integer studentId = (id == null ? null : Integer.parseInt(id));
        SelectedCourse selectedCourse = new SelectedCourse();
        selectedCourse.setStudentId(studentId);

        SelectedCourseDao selectedCourseDao = new SelectedCourseDao();
        List<SelectedCourse> selectedCourseList = selectedCourseDao.getSelectedCourseList(selectedCourse, new Page(1, 999));
        int[] courseId = new int[selectedCourseList.size()];

        for (int i = 0; i < courseId.length; i++) {
            courseId[i] = selectedCourseList.get(i).getCourseId();
        }

        CourseDao courseDao = new CourseDao();
        List<Course> courseList = courseDao.getCourse(courseId);

        response.setContentType("application/json; charset=UTF-8");
        try {
            response.getWriter().write(JSONArray.fromObject(courseList).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
